import axios from 'axios';
import Vue from 'vue';
import { Loading,Message } from 'element-ui';
import store from '../store'

axios.interceptors.response.use(function(response){
    if (response.status === 200) {
        // console.log(response)
        if (response.data.status !== 0) {
            if(response.data.status===-3000){
                store.commit('logout');
            }
            Message.error({message:response.data.msg})
            return Promise.reject(response);
        }else{
            return Promise.resolve(response);
        }
    } else {
        Message.error({message:'网络故障，请稍后再试'})
        return Promise.reject(response.data);
    }
}, function(error) {
    return Promise.reject(error);
})

export function fetch(url, params = {}, method = 'GET', { withMask = true, ...config } = {}) {
    if (!url) {
        throw new Error('interface path not found');
    }

    let isGet = method.toUpperCase() === 'GET';

    let loadingInstance = null;
    if(withMask){
        loadingInstance = Loading.service({text:'加载中，请稍候'});
    }
    
    return new Promise((resolve, reject) => {
        axios({
            url: url,
            method,
            params: isGet ? params : '',
            data: isGet ? '' : params,
            ...config
        }).then(rep => {
            loadingInstance && loadingInstance.close();
            resolve(rep);
        }, err => {
            loadingInstance && loadingInstance.close();
            reject(err);
        });
    });
}

export function fetchAll(...promises) {
    let loadingInstance = Loading.service({ text: '加载中，请稍候' });
    return Promise.all(promises).then(rep => {
        loadingInstance.close();
        return rep;
    }, err => {
        loadingInstance.close();
        return err;
    });
}

Vue.prototype.$fetch = fetch;
Vue.prototype.$fetchAll = fetchAll;
